package pw_reader

import (
	"bufio"
	"fmt"
	"github.com/spf13/viper"
	"io"
	"os"
	"strings"
	"unicode"
)

func Read(rowindex int64) {

	res := viper.Get("reader-path")

	var stIndex int64
	if rowindex != 0 {
		stIndex = rowindex
	} else {
		index := viper.Get("reader-index")
		if index == nil {
			stIndex = 0
		}
		stIndex = int64(index.(int))
	}

	file, err := os.OpenFile(res.(string), os.O_RDWR, 0666)
	if err != nil {
		fmt.Println("Open file error!", err)
		return
	}
	defer file.Close()

	buf := bufio.NewReader(file)
	var count int64 = 0
	var endrow int64 = 0

	for {
		line, err := buf.ReadString('\n') //以'\n'为结束符读入一行
		if err != nil || io.EOF == err {
			break
		}
		endrow++
		if line == "" {
			break
		}
		if line == "" || !IsChinese(line) {
			continue
		}
		if endrow > stIndex {
			line = strings.Replace(line, " ", "", -1)
			line = strings.Replace(line, "\n", "", -1)
			fmt.Println(endrow, "=>", line)
			count++
		}
		if count > 10 {
			break
		}

	}
	viper.Set("reader-index", endrow)
	viper.WriteConfig()

}

func IsChinese(str string) bool {
	var count int
	for _, v := range str {
		if unicode.Is(unicode.Han, v) {
			count++
			break
		}
	}
	return count > 0
}
